package com.ly.user_system.common;

import com.ly.user_system.exception.LyException;
import com.ly.user_system.log.LogMessage;
import com.ly.user_system.utils.R;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        LogMessage.errorLog(e,"参数校验异常: {}", e.getMessage());
        String message = e.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining("; "));
        return ResponseUtils.fail(ResultCode.PARAM_VALID_ERROR.getCode(), message);
    }


    /**
     * 处理其他所有异常
     */
    @ExceptionHandler(LyException.class)
    public R<Void> handleCusException(LyException e) {
        String message = e.getMessage();
        LogMessage.errorLog(e,e.getFormatStr(), message);
        return ResponseUtils.fail(e.getCode(), message);
    }

    /**
     * 处理其他所有异常
     */
    @ExceptionHandler(Exception.class)
    public R<Void> handleException(Exception e) {
        LogMessage.errorLog(e,"系统异常: {}", e.getMessage() );
        return ResponseUtils.fail(ResultCode.FAILURE.getCode(), "系统繁忙，请稍后再试，异常信息:"+e.getMessage());
    }
}
